/**
 * @(#)BaiduDituService.java, 2013-2-9. Copyright 2013 RENREN, Inc. All rights
 *                            reserved. RENREN PROPRIETARY/CONFIDENTIAL. Use is
 *                            subject to license terms.
 */
package com.wennimei.service;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wennimei.domain.baidu.Place;
import com.wennimei.util.HttpUtil;

/**
 * @author shichen.feng@renren-inc.com
 */
@Service
public class BaiduDituService {
    private static final String key = "530235711a980962aa5da71b28b57508";

    @SuppressWarnings("unchecked")
    public List<Place> getPlaces(String query, String bounds, String location,
            String radius, String region) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("http://api.map.baidu.com/place/search?key=" + key);
            if (null != query)
                sb.append("&query=" + URLEncoder.encode(query, "utf-8"));
            if (null != bounds)
                sb.append("&bounds=" + bounds);
            if (null != location)
                sb.append("&location=" + location);
            if (null != radius)
                sb.append("&radius=" + radius);
            if (null != region)
                sb.append("&region=" + URLEncoder.encode(region, "utf-8"));
            sb.append("&output=json");
            String json = HttpUtil.get(sb.toString());
            Gson gson = new Gson();
            Map<String, Object> map = gson.fromJson(json,
                    new TypeToken<Map<String, Object>>() {}.getType());

            List<Place> result = new ArrayList<Place>();
            List<Map<String, Object>> list = (List<Map<String, Object>>) map
                    .get("results");
            for (Map<String, Object> m: list) {
                Place place = new Place((String) m.get("name"),
                        (Map<String, Double>) m.get("location"),
                        (String) m.get("address"), (String) m.get("telephone"),
                        (String) m.get("uid"), (String) m.get("detail_url"));
                result.add(place);
            }

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
